package com.demiroot.server.pages;

import java.util.HashMap;

import com.demiroot.server.Cookie;
import com.demiroot.server.HTTPResponse;
import com.demiroot.server.HTTPResquest;
import com.demiroot.server.ServerSession;
import com.demiroot.server.ServerUtils;
import com.demiroot.server.pages.JavaPageResponse;
import com.demiroot.server.pages.Page;


public class Login implements Page{

	@Override
	public HTTPResponse getPage(HTTPResquest request) {
		String sessionId = request.getHeader().getCookieValue("session");
		ServerSession session = null;
		if (sessionId != null) {
			session = request.getServer().getSession(sessionId);
		}
		if (session == null || session.hasExpired()) {
			session = new ServerSession(request.getServer());
			request.getServer().addSession(session);
		}
		session.updateExpire();
		String challenge = ServerUtils.randomMD5();
		session.setVar("challenge", challenge);

		HashMap<String, String> swap = new HashMap<String, String>();
		swap.put("$Challenge","\"" + challenge + "\"");
		JavaPageResponse jpr = new JavaPageResponse(
				ServerUtils.generateFileFromTemplate("login.template", swap, request.getServer().getConfig()));
		
		jpr.addCookie(new Cookie("session", session.getSessionID()));
		
		return jpr;
	}

	
	public static boolean isThisYou(String file) {
		return file.equals("login");
	}

}
